package com.kl.forum.service;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.kl.forum.config.MyConfig;
import com.kl.forum.dao.JpushMapper;
import com.kl.forum.dao.JpushNumMapper;
import com.kl.forum.entity.Jpush;
import com.kl.forum.entity.JpushNum;
import com.kl.forum.enums.PushType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.kl.forum.util.DateUtil.formatDateToString;

@Service
public class PushService {

    private final static Logger logger = LoggerFactory.getLogger(PushService.class);

    @Autowired
    private MyConfig myConfig;

    @Autowired
    private JpushNumMapper jpushNumMapper;

    @Autowired
    private JpushMapper jpushMapper;

    //true 正式
    private  static  boolean apnsProduction = true;



    /**
     * userId 作为唯一标识
     * @param type 类型
     */
    public  void pushArticleMessage(Integer userId,String type){
        JPushClient jPushClient=new JPushClient(myConfig.getUSER_MASTER_SECRET(),myConfig.getUSER_APP_KEY(),null, ClientConfig.getInstance());
        PushPayload pushPayload= buildPushObject_all_alias_alert(userId,type);
        try {
            PushResult result=   jPushClient.sendPush(pushPayload);
            logger.info(result.toString());
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    public static PushPayload buildPushObject_all_alias_alert(Integer userId,String type) {
        String alert="";
        if (type.equals(PushType.Light.getCode())){
            alert="有人点赞了您,请前往app查看";
        }
        if (type.equals(PushType.Comment.getCode())){
            alert="有人评论了您,请前往app查看";

        }
        if (type.equals(PushType.Reply.getCode())){
            alert="有人回复了您,请前往app查看";

        }
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(String.valueOf(userId)))
                .setNotification(Notification.alert(alert))
                .setOptions(Options.newBuilder().setApnsProduction(apnsProduction).build()) //true生产环境
                .build();
    }

    /**
     *  push 数量+1   1 赞   2 评论   3回复，4系统消息
     */
    public void addPuhsNum(int userId, String type){
        Map map=new HashMap();
        try {
            map.put("userId",userId);
            JpushNum jpushNum= jpushNumMapper.findJpushNum(userId);
            if (jpushNum==null){
                JpushNum  jpushNum1=new JpushNum();
                if (type.equals(PushType.Light.getCode())){
                    jpushNum1.setFabulousNum(1);
                    jpushNum1.setUserId(userId);
                    jpushNumMapper.insertSelective(jpushNum1);
                }
                if (type.equals(PushType.Comment.getCode())){
                    jpushNum1.setCommentNum(1);
                    jpushNum1.setUserId(userId);
                    jpushNumMapper.insertSelective(jpushNum1);

                }
                if (type.equals(PushType.Reply.getCode())){
                    jpushNum1.setCommentNum(1);
                    jpushNum1.setUserId(userId);
                    jpushNumMapper.insertSelective(jpushNum1);
                }
                if(type.equals("4")){
                    jpushNum1.setSystemNum(1);
                    jpushNum1.setUserId(userId);
                    jpushNumMapper.insertSelective(jpushNum1);
                }
            }

            if(jpushNum!=null){
                if (type.equals(PushType.Light.getCode())){
                    jpushNum.setFabulousNum(jpushNum.getFabulousNum()+1);
                    jpushNumMapper.updateByPrimaryKeySelective(jpushNum);
                }
                if (type.equals(PushType.Comment.getCode())){
                    jpushNum.setCommentNum(jpushNum.getCommentNum()+1);
                    jpushNumMapper.updateByPrimaryKeySelective(jpushNum);

                }
                if (type.equals(PushType.Reply.getCode())){
                    jpushNum.setCommentNum(jpushNum.getCommentNum()+1);
                    jpushNumMapper.updateByPrimaryKeySelective(jpushNum);
                }
                if (type.equals("4")){
                    jpushNum.setSystemNum(jpushNum.getSystemNum()+1);
                    jpushNumMapper.updateByPrimaryKeySelective(jpushNum);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }



    }



    public     Map<String,PushPayload> punchMatchNotice(Collection<String>  userId){
        Map<String,PushPayload> map=new HashMap<>();
        String alert="您预约的晨起打卡挑战已经开始了！";
        Iterator<String> it=  userId.iterator();
        while (it.hasNext()){
            String id= it.next();
            Jpush jpush=new Jpush();
            jpush.setContent(alert);
            jpush.setCtime(formatDateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
            jpush.setTitle("系统消息");
            jpush.setUserId(Integer.valueOf(id));
            addPuhsNum(Integer.valueOf(id),"4");
            jpushMapper.insertSelective(jpush);
        }

        Map<String,String>  extras=new HashMap<>();
        extras.put("biaoshi","1");
        extras.put("leixing","0");
        extras.put("shuzhi","0");
//        Notification.ios(alert,extras);
//        Notification.android(alert,"",extras);

        PushPayload ios = PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(userId))
                .setNotification(Notification.ios(alert,extras))
//                .setNotification(Notification.android(alert,"",extras))
                .setOptions(Options.newBuilder().setApnsProduction(apnsProduction).build()) //true生产环境
                .build();


        PushPayload android=  PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(userId))
//                .setNotification(Notification.ios(alert,extras))
                .setNotification(Notification.android(alert,"",extras))
                .setOptions(Options.newBuilder().setApnsProduction(apnsProduction).build()) //true生产环境
                .build();

        map.put("android",android);
        map.put("ios",ios);

        return map;
    }

    /**
     * userId 作为唯一标识
     * @param
     */
    public  void pushMatchMessage(Collection<String>  userId){
        JPushClient jPushClient=new JPushClient(myConfig.getUSER_MASTER_SECRET(),myConfig.getUSER_APP_KEY(),null, ClientConfig.getInstance());
        Map<String,PushPayload> map= punchMatchNotice(userId);
        try {
            jPushClient.sendPush(map.get("ios"));
            PushResult result=   jPushClient.sendPush(map.get("android"));
            logger.info(result.toString());
        }catch (Exception e){
            e.printStackTrace();
        }

    }



}
